<?php
declare(strict_types=1);
namespace app\controller;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use think\exception\HttpResponseException;
use think\facade\Log;
use think\Request;
use think\Response;
use app\model\Admin as AdminModel;

/**
 * api根类
 */
class Base
{
    protected $page_num;
    protected $page_size;
    protected $request;
    protected $role_id;

    public function __construct(Request $request){
        $this->request = $request;
        $param = $request->param();
        Log::write($request->header('authorization2'));
        Log::write(json_encode($param));
        $this->page_num = $param['page_num'] ?? 1;
        $this->page_size = $param['page_size'] ?? config('app.page_size');

        //登录token 状态验证
        $token = $request->header('authorization');
        $this->checkToken($token);
    }

    /**
     * 创建token
     * @param $item
     * @param $expire_time
     * @param $create_time
     * @return string
     */
    protected function createToken($item,$expire_time,$create_time)
    {
        $secret = config('app.secret');      //密匙
        $payload = [
            'iss'=>'sol',                //签发人(官方字段:非必需)
            'exp'=>$expire_time,     //过期时间(官方字段:非必需)
            'aud'=>'admin',              //受众(官方字段:非必需)
            'nbf'=>$create_time,               //生效时间(官方字段:非必需)
            'iat'=>$create_time,               //签发时间(官方字段:非必需)
            'data'=>$item              //自定义字段
        ];
        $token = JWT::encode($payload,$secret,config('app.token_sign'));
        return $token;
    }

    /**
     * 验证token
     * @param $token
     * @return string
     */
    protected function checkToken($token)
    {
        $code = 401;
        $msg = '';
        $result = '';
        try {
            $result = JWT::decode($token, config('app.secret'), [config('app.token_sign')]);
            $msg = '验证成功';
            $code = 200;
        } catch (SignatureInvalidException $signatureInvalidException) {
            $msg = 'token 不正确';
            $code = 401;
        } catch (BeforeValidException $beforeValidException) {
            $msg = 'token 未生效';

        } catch (\Firebase\JWT\ExpiredException $expiredException) {
            $msg = 'token 过期';
        } catch (\DomainException $domainException) {
            $msg = 'token 格式不正确';
        }catch (\Exception $e) {
            $msg = 'token 验证失败';
        }
        $admin_id = $result ? $result->data->admin_id : -1;
        if( $code !== 200 || $admin_id < 0 ){
            $this->create_err([],$msg,$code);
        }
        $this->role_id = AdminModel::where('id',$admin_id)->value('role_id');
    }

    /**
     * @param $data
     * @param string $msg
     * @param int $code
     * @param string $type
     * @return Response 统一设置api返回
     */
    protected function create($data, string $msg = '', int $code = 200, string $type = 'json'){
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return Response::create($result,$type);
    }

    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param mixed   $data   要返回的数据
     * @param integer $code   返回的code
     * @param mixed   $msg    提示信息
     * @param string  $type   返回数据格式
     * @param array   $header 发送的Header信息
     * @return void
     */
    protected function create_err($data, string $msg = '', int $code = 200, string $type = 'json', array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }
}